#include <webx/route.h>
#include <webx/route.h>

class GetModuleList : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(GetModuleList)

int GetModuleList::process()
{
	param_int(port);
	param_string(host);
	param_string(flag);
	param_string(path);

	webx::CheckSystemRight(this);

	if (host.length() > 0)
	{
		HttpRequest request(this->request->getPath());

		request.setParameter("flag", flag);
		request.setParameter("path", path);

		SmartBuffer data = request.getResult(host, port);

		if (data.isNull()) return simpleResponse(XG_ERROR);

		out << data.str();

		return XG_OK;
	}

	int res = 0;
	size_t pos = app->getPath().length();
	JsonElement arr = json.addArray("list");

	if (flag == "H")
	{
		string name = path::name(path);

		path = app->getPath() + path::parent(path) + "/";

		JsonElement data;
		vector<string> vec;

		stdx::GetFolderContent(vec, path, eFILE);

		std::sort(vec.begin(), vec.end(), [](const string& a, const string& b){
			return a > b;
		});

		for (string& item : vec)
		{
			if (item.find(name.c_str()) == 0)
			{
				if (item == name) continue;

				item = path + item;

				if (res > 10)
				{
					path::remove(item);

					continue;
				}

				int len = path::size(item);
				time_t utime = path::mtime(item);

				data = arr[res++];

				data["size"] = len;
				data["path"] = item.substr(pos);
				data["utime"] = DateTime(utime).toString();
			}
		}
	}
	else
	{
		JsonElement data;
		set<string> fileset;
		map<string, CgiMapData> cgimap;
		string filter = stdx::tolower(path);

		app->getCgiMap(cgimap);

		for (const auto& item : cgimap)
		{
			if (item.second.flag == CgiMapData::URL_FLAG) continue;

			string path = item.second.url;
			string extname = stdx::tolower(path::extname(path));

			if (extname == "so" || extname == "dll")
			{
				string tmp = path.substr(pos);

				if (tmp.find("cgi/bin") == 0) continue;
				if (tmp.find("etc/plugin/bin") == 0) continue;
				if (tmp.find("app/confile/cgi") == 0) continue;
				if (tmp.find("app/workspace/cgi") == 0) continue;

				if (filter.length() > 0 && path.find(filter) == string::npos) continue;

				if (fileset.insert(path).second)
				{
					int len = path::size(path);
					time_t utime = path::mtime(path);

					data = arr[res++];

					data["size"] = len;
					data["path"] = path.substr(pos);
					data["utime"] = DateTime(utime).toString();

					data.addArray("list").add() = item.first;
				}
				else
				{
					data["list"].add() = item.first;
				}
			}
		}
	}

	json["count"] = res;
	json["code"] = res;
	out << json;

	return XG_OK;
}